
var mysql = require('mysql');
var config = require('../config/default.js')

var pool  = mysql.createPool({
  host     : config.database.HOST,
  user     : config.database.USERNAME,
  password : config.database.PASSWORD,
  database : config.database.DATABASE,
  port     : config.database.PORT
});


let query = ( sql, values ) => {
  return new Promise(( resolve, reject ) => {
    pool.getConnection( (err, connection) => {
      if (err) {
        reject( err )
      } else {
        connection.query(sql, values, ( err, rows) => {
          if ( err ) {
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  })
}

let article =
    `create table if not exists articles(
      id INT NOT NULL AUTO_INCREMENT,
      name VARCHAR(100) NOT NULL COMMENT '文章名',
      content VARCHAR(100) NOT NULL COMMENT '内容',
      moment VARCHAR(100) NOT NULL COMMENT '创建时间',
      PRIMARY KEY ( id )
    );`

let createTable = ( sql ) => {
  return query( sql, [] )
}
// 建表
createTable(article)
// 保存文章
exports.insertData = ( value ) => {
  let _sql = "insert into articles set name=?,content=?,moment=?;"
  return query( _sql, value )
}
//通过名字获取文章
exports.findArticleByName = ( name ) => {
  let _sql = `select * from articles where name="${name}";`
  return query( _sql)
}
//获取文章
exports.findArticle = (  ) => {
  let _sql = `select * from articles;`
  return query( _sql)
}